import React from 'react'
import './assets/style.scss'
import { useNavigate } from 'react-router-dom';
import { Button, Form, Input, message } from 'antd';
import {doLogin} from '@a/login.js'
import { useDispatch } from "react-redux";
import {initLogin, shouldAutoApps} from '@s/modules/user'
import {pushUser} from '@u'
export default function Login() {
  const dispatch = useDispatch() //修改公共状态中的值
 
const navigates = useNavigate()
//表单提交成功的回调
  const onFinish = (values) => {
  doLogin({values}).then(res => {
    console.log(res);
    if ( res.data.code ===200) {
      const { role, userInfo, token } = res.data.data;
      // localStorage.setItem('userInfo', JSON.stringify(userInfo))
      // localStorage.setItem('token', token)
      // localStorage.setItem('role', role)
      pushUser({ role, userInfo, token }) //调用储存到本地的函数
      dispatch(initLogin(res.data.data))//储存在redux中
     
      message.success(res.data.msg, 2, () => {
        navigates('/itemlists')
        dispatch(shouldAutoApps())
        // navigates(0)
      })
    }
  })
  };
  //表单提交成功的回调

  const onFinishFailed = (errorInfo) => {  //表单提交失败的回调
    console.log('Failed:', errorInfo);
  };

//表单重置
  const [form] =Form.useForm()
  
  const onReset = () => {
    form.resetFields();
  };
   //表单重置
  return (
    <div className='loginActive'>
      <div className="loginFrom">
      <Form
      form={form} 
      name="basic"
      labelCol={{
        span: 8,
      }}
      wrapperCol={{
        span: 16,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="userName"
        rules={[
          {
            required: true,
            message: '可以是数字字母下划线，5到10位数',
            pattern: /^\w{5,10}[a-zA-Z1-9]$/
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="pwd"
        rules={[  //表单校验规则
          {
            required: true,
            message: '可以是数字字母下划线，5到10位数',
            pattern: /^\w{5,10}[a-zA-Z1-9]$/
          },
        ]}
      >
        <Input.Password />
      </Form.Item>

      
      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
         登录
        </Button>
        <Button htmlType='reset' onClick={onReset}>重置</Button>
      </Form.Item>
    </Form>
      </div>
    </div>
  )
}
